package com.anyou.mall.goo.goods.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.anyou.common.exception.ServiceException;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.StringUtils;
import com.anyou.mall.goo.goods.domain.GooGoods;
import com.anyou.mall.goo.goods.domain.LiGoodsSku;
import com.anyou.mall.goo.goods.dto.GoodsOperationDTO;
import com.anyou.mall.goo.goods.dto.GoodsParamsDTO;
import com.anyou.mall.goo.goods.dto.GoodsSearchParams;
import com.anyou.mall.goo.goods.mapper.LiGoodsSkuMapper;
import com.anyou.mall.goo.goods.service.ILiGoodsSkuService;
import com.anyou.mall.goo.goods.vo.GoodsSkuVO;
import com.anyou.mall.goo.goods.vo.GoodsVO;
import com.anyou.mall.goo.goodsSku.domain.GooGoodsSku;
import com.anyou.mall.goo.goodsSpecs.domain.GooGoodsSpecs;
import com.anyou.mall.goo.goodsSpecs.domain.GooGoodsSpecsValue;
import com.anyou.mall.goo.goodsSpecs.mapper.GooGoodsSpecsMapper;
import com.anyou.mall.goo.goodsSpecs.mapper.GooGoodsSpecsValueMapper;
import com.anyou.mall.goo.specs.domain.SpeSpecs;
import com.anyou.mall.goo.specs.domain.SpeSpecsValue;
import com.anyou.mall.parts.domain.PlaPartsClassify;
import com.anyou.mall.parts.service.IPlaPartsClassifyService;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anyou.mall.goo.goods.mapper.LiGoodsMapper;
import com.anyou.mall.goo.goods.service.ILiGoodsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * goodsService业务层处理
 *
 * @author xiaQ
 * @date 2023-09-15
 */
@Service
public class LiGoodsServiceImpl  extends ServiceImpl<LiGoodsMapper, GooGoods> implements ILiGoodsService
{
    @Autowired
    private LiGoodsMapper liGoodsMapper;

    @Autowired
    private CarPartsShopMapper carPartsShopMapper;

    @Autowired
    private LiGoodsSkuMapper goodsSkuMapper;

    @Autowired
    private GooGoodsSpecsMapper goodsSpecsMapper;

    @Autowired
    private GooGoodsSpecsValueMapper goodsSpecsValueMapper;

    /**
     * 商品规格
     */
    @Autowired
    private ILiGoodsSkuService goodsSkuService;

    /**
     * 商品分类
     */
    @Autowired
    private IPlaPartsClassifyService laPartsClassifyService;

    /**
     * 查询goods
     *
     * @param id goods主键
     * @return goods
     */
    @Override
    public GoodsVO selectLiGoodsById(Long id)
    {
        //查询商品信息
        GooGoods goods = this.getById(id);
        if (goods == null) {
            log.error("商品ID为" + id + "的商品不存在");
            throw new ServiceException("商品已下架或者不存在");
        }
        GoodsVO goodsVO = new GoodsVO();
        //赋值
        BeanUtils.copyProperties(goods, goodsVO);
        //商品id
        goodsVO.setGoodsId(goods.getGoodsId());

        //规格list
        List<SpeSpecs> specsList = goodsSpecsMapper.getListByGoodsId(goods.getGoodsId());
        if(!specsList.isEmpty()){
            specsList.forEach(e -> {
                List<SpeSpecsValue> specsValueList = goodsSpecsValueMapper.getListByGoodsSpecsId(e.getGoodsSpecsId());
                e.setSpecsValueList(specsValueList);
            });
            goodsVO.setSpecsList(specsList);
        }

        //商品sku赋值
        List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goods.getGoodsId().toString());
        if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
            goodsVO.setSkuList(goodsListByGoodsId);
        }
        //商品分类名称赋值
        String categoryPath = goods.getCategoryPath();
        if (CharSequenceUtil.isNotEmpty(categoryPath)) {
            List<String> categoryName = new ArrayList<>();
            String[] strArray = categoryPath.split(",");
            List<PlaPartsClassify> plaPartsClassifyList = laPartsClassifyService.listByIds(Arrays.asList(strArray));
            for (PlaPartsClassify classify : plaPartsClassifyList) {
                categoryName.add(classify.getPartsClassifyName());
            }
            goodsVO.setCategoryName(categoryName);
        }
        //参数非空则填写参数
        if (CharSequenceUtil.isNotEmpty(goods.getGoodParams())) {
            goodsVO.setGoodsParamsDTOList(JSONUtil.toList(goods.getGoodParams(), GoodsParamsDTO.class));
        }
        return goodsVO;
    }

    /**
     * 查询goods列表
     *
     * @param goodsSearchParams
     * @return goods
     */
    @Override
    public List<GooGoods> selectLiGoodsList(GoodsSearchParams goodsSearchParams)
    {
        List<GooGoods> liGoods = liGoodsMapper.selectList(goodsSearchParams.queryWrapper());
        liGoods.forEach(goods->{
            //商品分类名称赋值
            List<String> categoryNames = new ArrayList<>();
            String categoryPath = goods.getCategoryPath();
            String[] strArray = categoryPath.split(",");
            List<PlaPartsClassify> plaPartsClassifyList = laPartsClassifyService.listByIds(Arrays.asList(strArray));
            for (PlaPartsClassify classify : plaPartsClassifyList) {
                categoryNames.add(classify.getPartsClassifyName());
            }
            String classNames = categoryNames.stream().map(String::valueOf).collect(Collectors.joining(","));
            goods.setCategoryNameStr(classNames);
        });
        return liGoods;
    }

    /**
     * 新增goods
     *
     * @param  goodsOperationDTO
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLiGoods(GoodsOperationDTO goodsOperationDTO)
    {
        GooGoods goods = new GooGoods(goodsOperationDTO);
        if(StringUtils.isNotEmpty(goodsOperationDTO.getCategoryPath())){
            String[] split = goodsOperationDTO.getCategoryPath().split(",");
            //存入1级分类id
            goods.setLavelOneId(Long.parseLong(split[0]));
        }
        //检查商品
        this.checkGoods(goods);
        //向goods加入图片
        if (goodsOperationDTO.getGoodsGalleryList() !=null) {
            this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList(), goods);
        }
        //添加商品参数
        if (goodsOperationDTO.getGoodsParamsDTOList() != null && !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
            //给商品参数填充值
            goods.setGoodParams(JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
        }
        //添加商品
        this.save(goods);

        //4.商品规格  goo_goods_specs   goo_goods_specs_value
        if(goods.getIsJf()!=1){
            insertGoodsSpecs(goodsOperationDTO.getSpecsList(),goods.getGoodsId());

            //添加商品sku信息
            /*this.goodsSkuService.add(goods, goodsOperationDTO);*/
            this.insertGoodsSku(goodsOperationDTO.getSkuList(),goods.getGoodsId());
        }
        return 1;
    }

    public void insertGoodsSpecs(List<SpeSpecs> list, Long goodsId){
        //商品修改时 先删除相关数据 再新增
        goodsSpecsMapper.delete(new LambdaQueryWrapper<GooGoodsSpecs>().eq(GooGoodsSpecs::getGoodsId,goodsId));
        goodsSpecsValueMapper.delete(new LambdaQueryWrapper<GooGoodsSpecsValue>().eq(GooGoodsSpecsValue::getGoodsSpecsId,goodsId));
        if(!list.isEmpty()){
            list.forEach(specs -> {
                GooGoodsSpecs goodsSpecs = new GooGoodsSpecs();
                goodsSpecs.setGoodsId(goodsId);
                goodsSpecs.setSpecsId(specs.getSpecsId());
                goodsSpecsMapper.insert(goodsSpecs);
                if(!specs.getSpecsValueList().isEmpty()){
                    specs.getSpecsValueList().forEach(specsValue -> {
                        GooGoodsSpecsValue goodsSpecsValue = new GooGoodsSpecsValue();
                        goodsSpecsValue.setGoodsId(goodsId);
                        goodsSpecsValue.setGoodsSpecsId(goodsSpecs.getGoodsSpecsId());
                        goodsSpecsValue.setSpecsValueId(specsValue.getSpecsValueId());
                        goodsSpecsValueMapper.insert(goodsSpecsValue);
                    });
                }
            });
        }
    }

    private void insertGoodsSku(List<LiGoodsSku> list, Long goodsId) {
        if(!list.isEmpty()){
            list.forEach(e -> {
                LiGoodsSku sku = new LiGoodsSku();
                sku.setGoodsId(goodsId);
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(e.getSpecsIds())){
                    sku.setSpecsIds(e.getSpecsIds());
                }
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(e.getSpecsNames())){
                    sku.setSpecsNames(e.getSpecsNames());
                }
                sku.setSpecsCompose(e.getSpecsCompose());
                sku.setSimpleSpecs(e.getSpecsCompose());
                sku.setPrice(e.getPrice());
                sku.setQuantity(e.getQuantity());
                sku.setSpecsValue(e.getSpecsValue());
                goodsSkuMapper.insert(sku);
            });
        }
    }

    @Override
    public Boolean upAndDownGoods(List<String> goodsIds, String goodsStatusEnum) {
        boolean result;

        //如果商品为空，直接返回
        if (goodsIds == null || goodsIds.isEmpty()) {
            return true;
        }

        LambdaUpdateWrapper<GooGoods> updateWrapper = new LambdaUpdateWrapper<GooGoods>();
        updateWrapper.set(GooGoods::getMarketEnable, goodsStatusEnum);
        updateWrapper.in(GooGoods::getGoodsId, goodsIds);
        result = this.update(updateWrapper);
        return result;
    }


    /**
     * 检查商品信息
     * 如果商品是虚拟商品则无需配置配送模板
     * 如果商品是实物商品需要配置配送模板
     * 判断商品是否存在
     * 判断商品是否需要审核
     * 判断当前用户是否为店铺
     *
     * @param goods 商品
     */
    private void checkGoods(GooGoods goods) {
        //检查商品是否存在--修改商品时使用
        if (goods.getGoodsId() != null) {
            this.checkExist(goods.getGoodsId());
        } else {
            //评论次数
            goods.setCommentNum(0);
            //购买次数
            goods.setBuyCount(0);
            //购买次数
            goods.setQuantity(0);
            //商品评分
            goods.setGrade(100.0);
        }

        //获取商品系统配置决定是否审核
        /*Setting setting = settingService.get(SettingEnum.GOODS_SETTING.name());
        GoodsSetting goodsSetting = JSONUtil.toBean(setting.getSettingValue(), GoodsSetting.class);*/

        // 审核状态（0待审核 1通过 2不通过）
        if(goods.getIsJf()==1){
            goods.setAuditStatus("1");
        }else{
            goods.setAuditStatus("0");
        }
        //判断当前用户是否为店铺
        /*if (goods.getStoreId()!=0 && goods.getStoreId()!=null) {
            *//*StoreVO storeDetail = this.storeService.getStoreDetail();
            if (storeDetail.getSelfOperated() != null) {
                goods.setSelfOperated(storeDetail.getSelfOperated());
            }*//*
            CarPartsShop carPartsShop = carPartsShopMapper.selectOne(new LambdaQueryWrapper<CarPartsShop>().
                    eq(CarPartsShop::getCarPartsShopId, goods.getStoreId()));
            if(carPartsShop == null){
                throw new ServiceException("商家编号错误或不存在");
            }
            goods.setStoreId(carPartsShop.getCarPartsShopId());     //店铺id
            goods.setStoreName(carPartsShop.getShopName()); //店铺name
        } else if (goods.getStoreId()==0){
            goods.setStoreId(0L);     //店铺id
            goods.setStoreName("平台自营"); //店铺name
        }else {
            throw new ServiceException("未登录店铺");
        }*/
    }

    /**
     * 判断商品是否存在
     *
     * @param goodsId 商品id
     * @return 商品信息
     */
    private GooGoods checkExist(Long goodsId) {
        GooGoods goods = liGoodsMapper.selectById(goodsId);
        if (goods == null) {
            log.error("商品ID为" + goodsId + "的商品不存在");
            throw new ServiceException("商品已下架或不存在");
        }
        return goods;
    }

    /**
     * 添加商品默认图片
     *
     * @param origin 图片
     * @param goods  商品
     */
    private void setGoodsGalleryParam(String origin, GooGoods goods) {
        /*GoodsGallery goodsGallery = goodsGalleryService.getGoodsGallery(origin);*/
        goods.setOriginal(origin);
    }

    @Override
    public void updateStock(Long goodsId, Integer quantity) {
        LambdaUpdateWrapper<GooGoods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(GooGoods::getQuantity, quantity);
        lambdaUpdateWrapper.eq(GooGoods::getGoodsId, goodsId);
        this.update(lambdaUpdateWrapper);
    }

    /**
     * 修改goods
     *
     * @param goodsOperationDTO
     * @return 结果
     */
    @Override
    public int updateLiGoods(GoodsOperationDTO goodsOperationDTO)
    {
        GooGoods goods = new GooGoods(goodsOperationDTO);
        goods.setUpdateTime(DateUtils.getNowDate());
        //检查商品信息
        this.checkGoods(goods);
        //向goods加入图片
        this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList(), goods);
        //添加商品参数
        if (goodsOperationDTO.getGoodsParamsDTOList() != null && !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
            goods.setGoodParams( JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
        }
        //修改商品
        this.updateById(goods);
        //修改商品sku信息
        /*this.goodsSkuService.update(goods, goodsOperationDTO);*/
        if(goods.getIsJf()!=1){
            // 修改商品sku
            goodsSkuService.updateSku(goods,goodsOperationDTO.getSkuList());
        }
        return 1;
    }

    /**
     * 批量删除goods
     *
     * @param ids 需要删除的goods主键
     * @return 结果
     */
    @Override
    public int deleteLiGoodsByIds(Long[] ids)
    {
        return liGoodsMapper.deleteLiGoodsByIds(ids);
    }

    /**
     * 删除goods信息
     *
     * @param id goods主键
     * @return 结果
     */
    @Override
    public int deleteLiGoodsById(Long id)
    {
        return liGoodsMapper.deleteLiGoodsById(id);
    }
}
